package com.wenhao.leetcode.medium;

import java.util.ArrayList;
import java.util.List;

/**
 * 题目:https://leetcode-cn.com/problems/spiral-matrix/
 * 螺旋矩阵
 *
 * 按层模拟的方法
 * 思路一定要清晰
 * 多用几个变量
 * 其实就是每次输出四个一维数组
 * 想清楚每一次输出的一维数组的起点和终点就好了
 *
 * @author Wenhao Tong
 * @Description
 * @create 2021-06-29 12:26
 */
public class LeetCode54 {
    public static void main(String[] args) {
        LeetCode54 leetCode54 = new LeetCode54();
        List<Integer> integers = leetCode54.spiralOrder(new int[][]{
                {1, 2, 3},
                {5,6,7},
                {9,10,11}
        });
        integers.stream().forEach((k) ->
                System.out.println(k));
    }

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int bottom = matrix.length - 1;
        while (top <= bottom && left <= right) {
            for (int i = left;i <= right;i++) {
                result.add(matrix[top][i]);
            }
            if (top++ >= bottom) {
                break;
            }
            for (int i = top;i <= bottom;i++) {
                result.add(matrix[i][right]);
            }
            if (right-- <= left) {
                break;
            }
            for (int i = right;i >= left;i--) {
                result.add(matrix[bottom][i]);
            }
            bottom--;
            for (int i = bottom;i >= top;i--) {
                result.add(matrix[i][left]);
            }
            left++;
        }
        return result;
    }
}
